import http.server
import json
import os
from urllib.parse import parse_qs
from socketserver import ThreadingTCPServer

# 配置
PORT = 9090
DATA_FILE = 'svn_data.json'
PASSWORD = '1234'

# 确保数据文件存在
if not os.path.exists(DATA_FILE):
    with open(DATA_FILE, 'w') as f:
        json.dump([], f)

# 读取项目数据
def read_projects():
    with open(DATA_FILE, 'r') as f:
        return json.load(f)

# 保存项目数据
def save_projects(projects):
    with open(DATA_FILE, 'w') as f:
        json.dump(projects, f, indent=4)

# HTML模板
HTML_TEMPLATE = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVN项目列表</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 100%;
            margin: 0 auto;
            padding: 15px;
            background-color: #f5f5f5;
            font-size: 14px;
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
            font-size: 20px;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow-x: auto;
        }
        .filter-input {
            width: 100%;
            padding: 6px 8px;
            margin-top: 5px;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 12px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #4CAF50;
            color: white;
        }
        tr:hover {
            background-color: #f9f9f9;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        .add-section {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .message {
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            border: 1px solid #d6e9c6;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
            border: 1px solid #ebccd1;
        }
    </style>
</head>
<body>
    <h1>SVN项目地址管理</h1>
    
    <div class="container">
        <table>
            <thead>
            <tr>
                <th>SVN地址<input type="text" class="filter-input" data-column="0" placeholder="筛选..."></th>
                <th>项目说明<input type="text" class="filter-input" data-column="1" placeholder="筛选..."></th>
                <th style="width: 120px;">项目经理<input type="text" class="filter-input" data-column="2" placeholder="筛选..."></th>
            </tr>
            </thead>
            <tbody>
            {table_rows}
            </tbody>
        </table>
    </div>
    
    <div class="container add-section">
        <h2>添加新项目</h2>
        {message}
        <form method="post">
            <div class="form-group">
                <label for="svn_url">SVN地址:</label>
                <input type="text" id="svn_url" name="svn_url" required>
            </div>
            <div class="form-group">
                <label for="description">项目说明:</label>
                <textarea id="description" name="description" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label for="manager">项目经理:</label>
                <input type="text" id="manager" name="manager" required>
            </div>
            <div class="form-group">
                <label for="password">口令:</label>
                <input type="password" id="password" name="password" required autocomplete="current-password">
            </div>
            <button type="submit">添加项目</button>
        </form>
    </div>
    <script>
        // 表格筛选功能
        document.addEventListener('DOMContentLoaded', function() {
            const filterInputs = document.querySelectorAll('.filter-input');
            const table = document.querySelector('table');
            const rows = table.querySelectorAll('tbody tr');

            filterInputs.forEach(input => {
                input.addEventListener('input', function() {
                    const column = parseInt(this.dataset.column);
                    const filterValue = this.value.toLowerCase().trim();

                    rows.forEach(row => {
                        const cell = row.querySelectorAll('td')[column];
                        const cellText = cell.textContent.toLowerCase();
                        const match = cellText.includes(filterValue);
                        row.style.display = match ? '' : 'none';
                    });
                });
            });
        });
    </script>
</body>
</html>'''

class SVNServerHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        # 读取项目数据
        projects = read_projects()
        
        # 生成表格行
        table_rows = ''
        for project in projects:
            table_rows += f'<tr><td>{project["url"]}</td><td>{project["description"]}</td><td>{project.get("manager", "")}</td></tr>'
        
        # 生成HTML响应
        html = HTML_TEMPLATE.replace('{table_rows}', table_rows).replace('{message}', '')
        
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(html.encode('utf-8'))
    
    def do_POST(self):
        # 读取表单数据
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        data = parse_qs(post_data)
        
        # 提取字段值
        password = data.get('password', [''])[0]
        svn_url = data.get('svn_url', [''])[0].strip()
        description = data.get('description', [''])[0].strip()
        manager = data.get('manager', [''])[0].strip()
        
        # 验证和错误收集
        errors = []
        if password != PASSWORD:
            errors.append("口令错误，请重试。")
        if not svn_url:
            errors.append("SVN地址不能为空")
        if not manager:
            errors.append("项目经理不能为空")
        if not description:
            errors.append("项目说明不能为空")
        if not password:
            errors.append("口令不能为空")
        
        # 检查SVN地址重复
        existing_projects = read_projects()
        for project in existing_projects:
            if project['url'] == svn_url:
                errors.append("SVN地址已存在，请使用不同的地址")
                break
        
        # 如果有错误，显示错误消息
        if errors:
            projects = read_projects()
            table_rows = ''
            for project in projects:
                table_rows += f'<tr><td>{project["url"]}</td><td>{project["description"]}</td><td>{project.get("manager", "")}</td></tr>'
            error_html = '<div class="message error"><ul>'
            for error in errors:
                error_html += f'<li>{error}</li>'
            error_html += '</ul></div>'
            html = HTML_TEMPLATE.replace('{table_rows}', table_rows).replace('{message}', error_html)
            
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(html.encode('utf-8'))
            return
        
        # 添加新项目
        projects = read_projects()
        projects.append({
            'url': svn_url,
            'description': description,
            'manager': data.get('manager', [''])[0]
        })
        save_projects(projects)
        
        # 生成成功响应
        table_rows = ''
        for project in projects:
            table_rows += f'<tr><td>{project["url"]}</td><td>{project["description"]}</td><td>{project.get("manager", "")}</td></tr>'
        success_message = '<div class="message success">项目添加成功！</div>'
        html = HTML_TEMPLATE.replace('{table_rows}', table_rows).replace('{message}', success_message)
        
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(html.encode('utf-8'))

if __name__ == '__main__':
    ThreadingTCPServer.allow_reuse_address = True
    with ThreadingTCPServer(('0.0.0.0', PORT), SVNServerHandler) as httpd:
        print(f'Starting server on port {PORT}...')
        httpd.serve_forever()